package com.gxitsky.async.design.listener;

import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author gxing
 * @desc TODO
 * @date 2022/7/27
 */
public class ServletAsyncListener implements AsyncListener {

    @Override
    public void onComplete(AsyncEvent asyncEvent) throws IOException {
        System.out.println("异步线程执行完成,回调【onComplete】");
    }

    @Override
    public void onError(AsyncEvent asyncEvent) throws IOException {
        System.out.println("异步线程错误,回调【onError】");
    }

    @Override
    public void onStartAsync(AsyncEvent arg0) throws IOException {
        System.out.println("开启异步线程,回调【onStartAsync】");
    }

    @Override
    public void onTimeout(AsyncEvent asyncEvent) throws IOException {
        System.out.println("异步线程执行超时,回调【onTimeout】");
        handleTimeoutOrError(asyncEvent, "Request Time Out");
    }

    private void handleTimeoutOrError(AsyncEvent event, String message) {
        PrintWriter writer = null;
        try {
//            future.cancel(true);
            HttpServletResponse response = (HttpServletResponse) event.getAsyncContext().getResponse();
            // HttpServletRequest request = (HttpServletRequest) event.getAsyncContext().getRequest();
            // request.getRequestDispatcher("/app/error.htm").forward(request, response);
            writer = response.getWriter();
            writer.print(message);
            writer.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            event.getAsyncContext().complete();
            if (writer != null) {
                writer.close();
            }
        }
    }

}
